package service.impl;

import domin.Account;
import mapper.AccountMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import service.AccountService;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

@Service("AccountService")
@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT,
        timeout = -1, rollbackFor = Exception.class, readOnly = false, transactionManager = "transactionManager")
public class AccountServiceImpl implements AccountService {
    @PostConstruct
    public void init() {
        System.out.println("初始化执行");
    }
    @PreDestroy
    public void destroy() {
        System.out.println("对象销毁执行");
    }

    @Autowired
    private AccountMapper mapper;

    public void setMapper(AccountMapper mapper) {
        this.mapper = mapper;
    }

    @Override
    public void transfer(String fromAccount, String toAccount, double money) {
//        根据名字查找账号
        Account fromName = mapper.findByName(fromAccount);
        Account toName = mapper.findByName(toAccount);
//改余额
        fromName.setMoney(fromName.getMoney() - money);
        toName.setMoney(toName.getMoney() + money);
//        数据库更新数据
        mapper.update(fromName);
        mapper.update(toName);

    }
}
